package edu.jimei.projecttachy.service;

import edu.jimei.projecttachy.controller.dto.AgentDto;
import edu.jimei.projecttachy.entity.Agent;
import edu.jimei.projecttachy.repository.AgentRepository;
import org.springframework.stereotype.Service;
import jakarta.persistence.EntityNotFoundException;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 智能体服务类，负责处理智能体相关的业务逻辑
 * 包括智能体的查询、创建、更新和删除等操作
 */
@Service
public class AgentService {

    private final AgentRepository agentRepository;

    /**
     * 构造函数，注入AgentRepository依赖
     * @param agentRepository 智能体数据访问接口
     */
    public AgentService(AgentRepository agentRepository) {
        this.agentRepository = agentRepository;
    }

    /**
     * 查询所有智能体
     * @return 所有智能体的DTO列表
     */
    public List<AgentDto> findAllAgents() {
        return agentRepository.findAll().stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
    }

    /**
     * 根据ID查询智能体
     * @param id 智能体ID
     * @return 智能体DTO（ Optional包装 ）
     */
    public Optional<AgentDto> findAgentById(Long id) {
        return agentRepository.findById(id)
                .map(this::convertToDto);
    }

    /**
     * 创建新智能体
     * @param agentDto 包含智能体信息的DTO对象
     * @return 保存后的智能体DTO
     */
    public AgentDto createAgent(AgentDto agentDto) {
        Agent agent = convertToEntity(agentDto);
        Agent savedAgent = agentRepository.save(agent);
        return convertToDto(savedAgent);
    }

    /**
     * 更新智能体信息
     * @param id 智能体ID
     * @param agentDto 包含更新信息的DTO对象
     * @return 更新后的智能体DTO
     * @throws EntityNotFoundException 当智能体不存在时抛出
     */
    public AgentDto updateAgent(Long id, AgentDto agentDto) {
        Agent existingAgent = agentRepository.findById(id)
                .orElseThrow(() -> new EntityNotFoundException("Agent not found with id: " + id));

        // Update fields from DTO
        existingAgent.setName(agentDto.name());
        existingAgent.setDescription(agentDto.description());
        existingAgent.setAvatarUrl(agentDto.avatarUrl());
        existingAgent.setCompatibleSources(agentDto.compatibleSources());
        // systemPrompt is not in AgentDto, handle separately if needed.

        Agent updatedAgent = agentRepository.save(existingAgent);
        return convertToDto(updatedAgent);
    }

    /**
     * 将AgentDto转换为Agent实体
     * @param agentDto 智能体DTO对象
     * @return 智能体实体对象
     */
    private Agent convertToEntity(AgentDto agentDto) {
        Agent agent = new Agent();
        agent.setName(agentDto.name());
        agent.setDescription(agentDto.description());
        agent.setAvatarUrl(agentDto.avatarUrl());
        agent.setCompatibleSources(agentDto.compatibleSources());
        return agent;
    }

    /**
     * 将Agent实体转换为AgentDto
     * @param agent 智能体实体对象
     * @return 智能体DTO对象
     */
    private AgentDto convertToDto(Agent agent) {
        return new AgentDto(
                agent.getId(),
                agent.getName(),
                agent.getDescription(),
                agent.getAvatarUrl(),
                agent.getCompatibleSources()
        );
    }

    /**
     * 删除智能体
     * @param id 智能体ID
     * @throws EntityNotFoundException 当智能体不存在时抛出
     */
    public void deleteAgent(Long id) {
        if (!agentRepository.existsById(id)) {
            throw new EntityNotFoundException("Agent not found with id: " + id);
        }
        agentRepository.deleteById(id);
    }


}